import { Stack, useRouter, useSegments, useRootNavigationState } from 'expo-router';
import { useColorScheme, Platform, SafeAreaView, View } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useFonts } from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';
import { useEffect } from 'react';
import React from 'react';
import { MaterialIcons } from '@expo/vector-icons';
import { Providers } from '../store/Provider';
import { useAuth } from '../store/auth/AuthContext';
import { Text, TouchableOpacity } from 'react-native';
import { ThemeProvider } from '../components/theme/ThemeContext';
import { useTheme } from '../components/theme/ThemeContext';
import Toast from 'react-native-toast-message';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import 'react-native-reanimated';

// 在 web 平台上禁用 findDOMNode 警告
if (Platform.OS === 'web') {
  const consoleError = console.error;
  console.error = (...args) => {
    if (args[0]?.includes?.('findDOMNode')) {
      return;
    }
    consoleError(...args);
  };
}

// 保持启动屏幕可见，直到字体加载完成
SplashScreen.preventAutoHideAsync();

class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean; error?: Error }
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error) {
    console.log('Error caught by boundary:', error);
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // 记录所有错误信息
    console.error('Caught by error boundary:');
    console.error('Error:', error);
    console.error('Component stack:', errorInfo.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 }}>
          <Text style={{ fontSize: 18, marginBottom: 10 }}>
            抱歉，应用程序出现了问题
          </Text>
          <Text style={{ color: '#666', textAlign: 'center', marginBottom: 20 }}>
            {this.state.error?.message || '请稍后重试'}
          </Text>
          <TouchableOpacity
            onPress={() => {
              this.setState({ hasError: false });
              // 可以在这里添加额外的重置逻辑
            }}
            style={{
              padding: 10,
              backgroundColor: '#007AFF',
              borderRadius: 5,
            }}
          >
            <Text style={{ color: '#fff' }}>重试</Text>
          </TouchableOpacity>
        </View>
      );
    }

    return this.props.children;
  }
}

export default function RootLayout() {
  const colorScheme = useColorScheme();
  const { theme } = useTheme();

  // 加载自定义字体
  const [fontsLoaded] = useFonts({
    // 这里可以添加自定义字体
  });



  useEffect(() => {
    if (fontsLoaded) {
      SplashScreen.hideAsync().catch(console.error);
    }
  }, [fontsLoaded]);

  if (!fontsLoaded) {
    return null;
  }

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <ErrorBoundary>
        <ThemeProvider>
          <Providers>
            <View style={{ flex: 1, backgroundColor: theme.colors.background }}>
              <StatusBar 
                style={colorScheme === 'dark' ? 'light' : 'dark'} 
              />
              <RootLayoutNav />
            </View>
          </Providers>
          <Toast />
        </ThemeProvider>
      </ErrorBoundary>
    </GestureHandlerRootView>
  );
}

// 将导航逻辑移到单独的组件中
function RootLayoutNav() {
  const { user, isLoading } = useAuth();
  const router = useRouter();
  const segments = useSegments();
  const navigationState = useRootNavigationState();
  const { theme } = useTheme();

  console.log('UserInit:', user);
  console.log('SegmentsInit:', segments);
  console.log('Navigation State KeyInit:', navigationState?.key);

  useEffect(() => {
    try {
      console.log('User:', user);
      console.log('Segments:', segments);
      console.log('Navigation State Key:', navigationState?.key);

      if (!navigationState?.key) return;

      const inAuthGroup = segments[0] === 'user';
      const isAuthScreen = segments[1] === 'login' || segments[1] === 'register';
      
      const navigate = async () => {
        try {
          if (!user && !inAuthGroup) {
            console.log('Redirecting to login page');
            router.replace('/user/login');
          } else if (user && isAuthScreen) {
            console.log('Redirecting to home page');
            router.replace('/(tabs)');
          }
        } catch (error) {
          console.error('Navigation failed:', error);
        }
      };

      navigate();
    } catch (error) {
      console.error('Navigation error:', error);
    }
  }, [user, segments, navigationState?.key]);

  if (isLoading) {
    return null;
  }

  return (
    <Stack 
      screenOptions={{
        headerShown: false,
        contentStyle: { 
          backgroundColor: theme.colors.background,
        },
        headerStyle: { 
          backgroundColor: theme.colors.card,
        },
        headerTintColor: theme.colors.text,
        headerShadowVisible: false,
        headerTitleStyle: { 
          color: theme.colors.text 
        },
      }}
    >
      <Stack.Screen 
        name="(tabs)" 
        options={{ 
          headerShown: false,
        }} 
      />
      <Stack.Screen 
        name="user/login" 
        options={{ 
          title: '登录',
          headerShown: true,
          presentation: 'card',
        }} 
      />
      <Stack.Screen 
        name="user/register" 
        options={{ 
          title: '注册',
          headerShown: true,
          presentation: 'card',
        }} 
      />
      <Stack.Screen 
        name="user/edit-profile" 
        options={{ 
          title: '编辑资料',
          headerShown: true,
          presentation: 'card',
        }} 
      />
      <Stack.Screen 
        name="topic" 
        options={{
          headerShown: true,
          headerStyle: { 
            backgroundColor: theme.colors.card 
          },
          headerTintColor: theme.colors.text,
          headerShadowVisible: false,
        }}
      />
      <Stack.Screen 
        name="artwork" 
        options={{
          headerShown: true,
          headerStyle: { 
            backgroundColor: theme.colors.card 
          },
          headerTintColor: theme.colors.text,
          headerShadowVisible: false,
        }}
      />
      <Stack.Screen 
        name="search" 
        options={{ 
          headerShown: false,
          presentation: 'modal'
        }} 
      />
    </Stack>
  );
}
